package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import dao.UserDao;
import exception.UserNotFoundException;
 
/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    static Logger LOGGER = Logger.getLogger(LoginServlet.class.getName());
    
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    	response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        // get request parameters for userID and password
        String user = request.getParameter("user");
        String pwd = request.getParameter("pwd");

        try {
        	boolean exists = UserDao.verifyUser(user, pwd);
        	if (exists) {
        		Cookie loginCookie = new Cookie("user",user);
                //setting cookie to expiry in 30 mins
                loginCookie.setMaxAge(30*60);
                response.addCookie(loginCookie);
                out.append("mainPage.jsp");
                LOGGER.info("User name connected " + user + " at "+ new Date().toString());
        	} else {
        		out.append("invalidPassword");
            	LOGGER.info("Invalid password " + pwd + " for user name "+ user);
        	}
        } catch(UserNotFoundException unfe) {
        	out.append("invalidUser");
        	LOGGER.info("Invalid user name" + user);
        } catch(Exception e) {
        	out.append("fail");
        	LOGGER.error("Could not verify user on login. Exception "+ e.getMessage());
        }
    }
    
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    	doPost(request, response);
    }
    
}